package com.A21MobileSales;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.A21.Object.A21OrderHeader;
import com.A21.Object.Global;
import com.A21.Object.MSTCustomer;
import com.A21.Object.MSTSettings;
import com.A21.Object.SpinnerObject;
import com.A21.Object.TrnDetail;
import com.A21.XMLSerialization.XmlSerializer;
import com.A21MobileSales.DataBase.DatabaseHelper;
import com.A21MobileSales.JsonServices.Upload;
import com.datecs.api.printer.Printer;
import com.datecs.api.printer.PrinterInformation;
import com.datecs.api.printer.ProtocolAdapter;

public class OrderHeader extends Activity {

	Spinner spnrAddress;
	Button btnAddSearch;
	DatabaseHelper objDBHelper;
	EditText Add1, Add2, Add3, Add4, CustomerName, DelDate, TrnDate, OrderId,
			Narration, CustomerPO;
	Button btnSave, btnPost, btnPrint,btnPrintDO;
	private String CustCode, CName, Id, TrnType, GST, GSTInc,DiscountType;
	public A21OrderHeader Header;
	String CurrentTableHeader;
	String CurrentTableDetail;
	MSTSettings setting;
	private BluetoothAdapter mBluetoothAdapter;
	Bitmap logoHeader,logoFooter;
	// Start Printing Variable //
	private Printer mPrinter;
	private ProtocolAdapter mProtocolAdapter;
	private PrinterInformation mPrinterInfo;
	private BluetoothSocket mBluetoothSocket; 
	private boolean mRestart;
	boolean printerfound;
	String StrXml, TrnName;
	private ArrayAdapter<SpinnerObject> SpinnerAdapter;
	private boolean onload=false;
	int NoOfReceipt;
	// end Printing Variable //
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.order_header);
		if (getIntent().hasExtra("Code")) {
			CustCode = getIntent().getStringExtra("Code");
		}
		if (getIntent().hasExtra("CName")) {
			CName = getIntent().getStringExtra("CName");
		}
		if (getIntent().hasExtra("Id")) {
			Id = getIntent().getStringExtra("Id");
		}
		if (getIntent().hasExtra("TrnType")) {
			TrnType = getIntent().getStringExtra("TrnType");
		}
		if (getIntent().hasExtra("GST")) {
			GST = getIntent().getStringExtra("GST");
		}
		if (getIntent().hasExtra("GSTInc")) {
			GSTInc = getIntent().getStringExtra("GSTInc");
		}
		
		if (getIntent().hasExtra("DiscountType")) {
			DiscountType = getIntent().getStringExtra("DiscountType");
		} 
		if(TrnType.equals("CW")){
			TrnName="Order"; 
			NoOfReceipt=Global.getMSTSettings().NoOfReceiptCW;
		}else if(TrnType.equals("CR")){
			TrnName="Invoice"; 
			NoOfReceipt=Global.getMSTSettings().NoOfReceiptCR;
		}else if(TrnType.equals("CA")){
			TrnName="Invoice"; 
			NoOfReceipt=Global.getMSTSettings().NoOfReceiptCA;
		}
		
		btnPrintDO = (Button) findViewById(R.id.btnPrintDO);
		setting = Global.getMSTSettings();
		if (TrnType.equals("CW")) {
			 if(!setting.PrintDO_CW){
				 btnPrintDO.setVisibility(View.GONE); 
			 } 
			CurrentTableHeader = "A21OPOrderHeader";
			CurrentTableDetail = "A21OPOrderDetail"; 
		} else if (TrnType.equals("CA")) { 
			 if(!setting.PrintDO_CA){
				 btnPrintDO.setVisibility(View.GONE); 
			 }  
			CurrentTableHeader = "A21OPCashInvoiceHeader";
			CurrentTableDetail = "A21OPCashInvoiceDetail";
		} else if (TrnType.equals("CR")) {  
			 if(!setting.PrintDO_CR){
				 btnPrintDO.setVisibility(View.GONE); 
			 } 
			btnPrintDO.setEnabled(setting.PrintDO_CR);
			CurrentTableHeader = "A21OPCreditInvoiceHeader";
			CurrentTableDetail = "A21OPCreditInvoiceDetail";
		}
		onload=true;
		//Common ObjC = new Common(OrderHeader.this);
	
		objDBHelper = new DatabaseHelper(this);
		byte[] bteLogo = objDBHelper.getImageLogo("PrintHeaderLogo");
		if (bteLogo != null) {
			Bitmap original = BitmapFactory.decodeByteArray(bteLogo, 0,
					bteLogo.length);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			original.compress(Bitmap.CompressFormat.JPEG, 100, out);
			logoHeader = BitmapFactory.decodeStream(new ByteArrayInputStream(out
					.toByteArray()));
		}
		
	   bteLogo = objDBHelper.getImageLogo("PrintFooterLogo");
		if (bteLogo != null) {
			Bitmap original = BitmapFactory.decodeByteArray(bteLogo, 0,
					bteLogo.length);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			original.compress(Bitmap.CompressFormat.JPEG, 100, out);
			logoFooter = BitmapFactory.decodeStream(new ByteArrayInputStream(out
					.toByteArray()));
		} 

		final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat dfDoc = new SimpleDateFormat("ddMMyy");

		if (!Id.equals("0")) {
			objDBHelper = new DatabaseHelper(this);
			Header = objDBHelper.GetOrderHeaderByIdOrCreatedTime(
					CurrentTableHeader, Id, true);
			GST = String.valueOf(Header.GST);
			GSTInc = String.valueOf(Header.GSTInc);
		} else { 
			Header = new A21OrderHeader();
			MSTCustomer customer = null;
			objDBHelper = new DatabaseHelper(this);
			try {
				customer = objDBHelper.GetCustomerByCode(CustCode);
			} catch (Exception e) {
				Toast.makeText(OrderHeader.this, e.getMessage(),
						Toast.LENGTH_SHORT).show();
			}
			Header.Add1 = customer.Add1;
			Header.Add2 = customer.Add2;
			Header.Add3 = customer.Add3;
			Header.Add4 = customer.Add4;
			Header.CName = customer.CName;
			Header.Id = 0;
			Header.Code = customer.Code;
			Date currentDate = new Date();
			Header.CreatedDate = df.format(currentDate);
			Header.DocDate = dfDoc.format(currentDate);
			Header.CreatedUser = Global.getLoggedInUser().User;
			Header.SalesPerson = Global.getLoggedInUser().Employee;
			Header.Currency = customer.Currency;
			Header.CustomerPO = "";
			Header.GST = Double.valueOf(GST);
			Header.GSTInc = customer.GSTInc == true ? 1 : 0;
			Header.TrnDate = Header.CreatedDate;
			Header.TrnType = TrnType;
			Header.Discount=0;
            Header.DiscountType=DiscountType;
            Header.ReservedField2="Billing Address";
		}
        
		OrderId = (EditText) findViewById(R.id.edtOrderId);
		CustomerName = (EditText) findViewById(R.id.edtCname);
		Add1 = (EditText) findViewById(R.id.edtAdd1);
		Add2 = (EditText) findViewById(R.id.edtAdd2);
		Add3 = (EditText) findViewById(R.id.edtAdd3);
		Add4 = (EditText) findViewById(R.id.edtAdd4);
		TrnDate = (EditText) findViewById(R.id.edtOrderDate);
		DelDate = (EditText) findViewById(R.id.edtDelDate);
		btnSave = (Button) findViewById(R.id.btnSave); 
		
		btnPost = (Button) findViewById(R.id.btnPost);
		btnPrint = (Button) findViewById(R.id.btnPrint);
		Narration = (EditText) findViewById(R.id.edtNarration);
		CustomerPO = (EditText) findViewById(R.id.edtCustomerPO);

		OrderId.setText(Header.Id == 0 ? "*Auto*" : Header.DocNo);
		CustomerName.setText(CName); 
		Narration.setText(Header.ReservedField1);
		Date DateDisp = null;
		try {
			DateDisp = df.parse(Header.TrnDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	    final DateFormat dfDisp = new SimpleDateFormat("dd-MM-yyyy");
		TrnDate.setText(dfDisp.format(DateDisp));
		//TrnDate.setEnabled(false);
		if(Header.DelDate!=null){ 
			try {
				DateDisp = df.parse(Header.DelDate);
			} catch (ParseException e) {
				e.printStackTrace();
			} 
			DelDate.setText(dfDisp.format(DateDisp));
		}
		
		DelDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar mcurrentDate = Calendar.getInstance();
				int mYear = mcurrentDate.get(Calendar.YEAR);
				int mMonth = mcurrentDate.get(Calendar.MONTH);
				int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
				DatePickerDialog mDatePicker = new DatePickerDialog(
						OrderHeader.this,
						new DatePickerDialog.OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {

								String formatedDate = dfDisp.format(Global
										.getDate(year, monthOfYear, dayOfMonth));
								DelDate.setText(formatedDate);
								Header.DelDate=formatedDate;
							}
						}, mYear, mMonth, mDay);
				mDatePicker.setTitle("Select date");
				mDatePicker.show();
			}
		});

		TrnDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar mcurrentDate = Calendar.getInstance();
				int mYear = mcurrentDate.get(Calendar.YEAR);
				int mMonth = mcurrentDate.get(Calendar.MONTH);
				int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
				DatePickerDialog mDatePicker = new DatePickerDialog(
						OrderHeader.this,
						new DatePickerDialog.OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								String formatedDate = dfDisp.format(Global
										.getDate(year, monthOfYear, dayOfMonth));
								TrnDate.setText(formatedDate);
								Header.TrnDate=formatedDate;
								Global.setA21OrderHeader(Header); 
							}
						}, mYear, mMonth, mDay);
				mDatePicker.setTitle("Select date");
				mDatePicker.show();
				
			}
		});

		  
		spnrAddress = (Spinner) findViewById(R.id.spnrAddress);
		objDBHelper = new DatabaseHelper(this); 
		SpinnerObject[] arrLoc = objDBHelper.GetCustomerLocations(CustCode);  
		btnAddSearch = (Button) findViewById(R.id.btnSearhNormal);
		btnAddSearch.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) { 
				if(onload){
				  SelectSpinnerItemByValue(spnrAddress,Header.ReservedField2);
				  onload=false;
				}
				spnrAddress.performClick();
			}
		});
		
		  
		SpinnerAdapter= new ArrayAdapter<SpinnerObject>(OrderHeader.this,  android.R.layout.simple_spinner_item, arrLoc); 
		SpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spnrAddress.setAdapter(SpinnerAdapter);  
		
		 
		
		spnrAddress.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> Adater, View v, int Pos,
					long ID) {
				
				SpinnerObject item=(SpinnerObject) spnrAddress.getSelectedItem ();  
				String SelectedItem=item.getCode();  
				if(!onload &  !Header.ReservedField2.equals(SelectedItem)){ 
			    Header.ReservedField2=SelectedItem;
				ArrayList<String> addDetails = new ArrayList<String>();
				if (SelectedItem.equals("Billing Address")) {
					addDetails = objDBHelper.GetCustomerInfo(CustCode);
					if (addDetails.size() != 0) {
						Add1.setText(addDetails.get(0) == null ? ""
								: addDetails.get(0));
						Add2.setText(addDetails.get(1) == null ? ""
								: addDetails.get(1));
						Add3.setText(addDetails.get(2) == null ? ""
								: addDetails.get(2));
						Add4.setText(addDetails.get(3) == null ? ""
								: addDetails.get(3));
					}
					
				}else if (SelectedItem.equals("None")) { 
						Add1.setText("");
						Add2.setText("");
						Add3.setText("");
						Add4.setText(""); 
				} else {   
					addDetails = objDBHelper.GetCustomerLocationDetails(SelectedItem, CustCode);
					if (addDetails.size() != 0) {
						Add1.setText(addDetails.get(0) == null ? ""
								: addDetails.get(0));
						Add2.setText(addDetails.get(1) == null ? ""
								: addDetails.get(1));
						Add3.setText(addDetails.get(2) == null ? ""
								: addDetails.get(2));
						Add4.setText(addDetails.get(3) == null ? ""
								: addDetails.get(3));
					} else {
						Add1.setText("");
						Add2.setText("");
						Add3.setText("");
						Add4.setText("");
					}

				}
				Header.Add1 = Add1.getText().toString();
				Header.Add2 = Add2.getText().toString();
				Header.Add3 = Add3.getText().toString();
				Header.Add4 = Add4.getText().toString();
				}
				 

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				Add1.setText(Header.Add1);
				Add2.setText(Header.Add2);
				Add3.setText(Header.Add3);
				Add4.setText(Header.Add4);
			}
		});

		btnSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TabActivity parent = (TabActivity) getParent();
				OrderDetail activitydet = (OrderDetail) parent
						.getLocalActivityManager().getActivity("Detail");
				objDBHelper = new DatabaseHelper(OrderHeader.this);
				try {

					Header.Add1 = Add1.getText().toString();
					Header.Add2 = Add2.getText().toString();
					Header.Add3 = Add3.getText().toString();
					Header.Add4 = Add4.getText().toString();
					Header.ReservedField1 = Narration.getText().toString();
					Header.DelDate = DelDate.getText().toString();
					Header.CustomerPO = CustomerPO.getText().toString();  
					
					SimpleDateFormat dfTrnDisp = new SimpleDateFormat(
							"dd-MM-yyyy HH:mm:ss"); 
					SimpleDateFormat dfTime = new SimpleDateFormat("HH:mm:ss");
					Date time = new Date();
					String strTime = dfTime.format(time);
					Header.TrnDate = TrnDate.getText().toString() + " "
							+ strTime; 
					Date DateTrn = null;
					try {
						DateTrn = dfTrnDisp.parse(Header.TrnDate);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					Header.TrnDate = df.format(DateTrn);
					
					if (!Header.DelDate.equals("")) {
						 time = new Date();
					    strTime = dfTime.format(time);
						Header.DelDate = Header.DelDate  + " "
								+ strTime; 
					    DateTrn = null;
						try {
							DateTrn = dfTrnDisp.parse(Header.DelDate);
						} catch (ParseException e) {
							e.printStackTrace();
						}
						Header.DelDate = df.format(DateTrn);
					}
					
					
					if (activitydet != null){
						Header.DiscountType=activitydet.DiscountType; 
						Header.Discount=activitydet.DiscountPer;
					}
					String[] HeaderIds = objDBHelper.SaveOrderHeader(
							CurrentTableHeader, Header);
					Header.Id = Integer.valueOf(HeaderIds[0]);
					if (activitydet != null) { 
						ArrayList<TrnDetail> list = activitydet.list;
						for (TrnDetail row : list) {
							row.HeaderId = Header.Id;
							row.Id=objDBHelper.SaveOrderDetail(CurrentTableDetail, row);
						}
						Header.DocNo = HeaderIds[1];
						OrderId.setText(Header.DocNo);
						activitydet.UpdateList(list);
					} 
					 
					Toast.makeText(OrderHeader.this,
							TrnName + " has been saved successfully.",
							Toast.LENGTH_SHORT).show();

				} catch (Exception e) {
					Toast.makeText(OrderHeader.this, e.getMessage(),
							Toast.LENGTH_SHORT).show();
				}

			}
		});

		btnPost.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (Header.Id != 0) {
					XmlSerializer ObjSerialize = new XmlSerializer();
					TelephonyManager telephonyManager = (TelephonyManager) OrderHeader.this
							.getSystemService(Context.TELEPHONY_SERVICE);
					String IMEI_Number = telephonyManager.getDeviceId();
					if (IMEI_Number == null) {
						IMEI_Number = Build.SERIAL;
					} 
					Header.IMEIID = IMEI_Number;
					Header.TrnDetails = getListCart();
					if(Header.TrnDetails.size()==0){
						Toast.makeText(OrderHeader.this,
								"No details entered.",
								Toast.LENGTH_SHORT).show();
						return;
					}
					ArrayList<A21OrderHeader> lstH=new ArrayList<A21OrderHeader>();
					lstH.add(Header);
					StrXml = ObjSerialize.objectToXml(lstH);
					new btnSyncTask().execute();
				} else {
					Toast.makeText(OrderHeader.this,
							"Please save the transaction before POST.",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		btnPrint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (printerfound) {
					if (Header.Id != 0) { 
						  printOrder(false); 
					} else {
						Toast.makeText(OrderHeader.this,
								"Please save the transaction before print.",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(OrderHeader.this,
							"Bluetooth printer not found or not paired",
							Toast.LENGTH_SHORT).show();
				}
			}
		}); 
		
		btnPrintDO.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (printerfound) {
					if (Header.Id != 0) {
						printOrder(true);
					} else {
						Toast.makeText(OrderHeader.this,
								"Please save the transaction before print.",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(OrderHeader.this,
							"Bluetooth printer not found or not paired",
							Toast.LENGTH_SHORT).show();
				}
			}
		}); 
		
		Add1.setText(Header.Add1);
		Add2.setText(Header.Add2);
		Add3.setText(Header.Add3);
		Add4.setText(Header.Add4);
		CustomerPO.setText(Header.CustomerPO);
		Global.setA21OrderHeader(Header); 
		mRestart = true;
	    waitForConnection();
	    
	}

	public  void SelectSpinnerItemByValue(Spinner spnr, String value)
	{ 
	    for (int position = 0; position < SpinnerAdapter.getCount(); position++)
	    {
	    	SpinnerObject item=(SpinnerObject) SpinnerAdapter.getItem(position);  
			String ItemVal=item.getCode();  
	        if(ItemVal.equals( value))
	        {
	            spnr.setSelection(position,false);
	            return;
	        }
	    }
	}
	
	
	   @Override
	  protected void onStop() {
	    super.onStop();
	     mRestart = false;               
       closeActiveConnection();
	  }
	
	// Sync All Details from server.
	private class btnSyncTask extends AsyncTask<String, Void, Void> {

		private ProgressDialog dialog = new ProgressDialog(OrderHeader.this);
		String StrMsg = null;

		protected void onPreExecute() {
			this.dialog.setMessage("Loading...");
			this.dialog.setCanceledOnTouchOutside(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... a) {
			try {

				String strUserName = Global.getLoggedInUser().User;
				String strPassword = Global.getLoggedInUser().strPassword;
				Upload ObjUL = new Upload(OrderHeader.this, strUserName,
						strPassword);
				ObjUL.PostTransaction(StrXml);
				StrMsg = "Success";
			} catch (Exception ex) {
				StrMsg = ex.getMessage();
			}

			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {

			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
				this.dialog = null;
			}
			try {
				if (StrMsg != null) {
					if (StrMsg.equals("Success")) {
						Toast.makeText(OrderHeader.this, "Transaction has been posted successfully!", Toast.LENGTH_SHORT).show();
						btnSave.setEnabled(false);
						btnPost.setEnabled(false);
					} else {
						Toast.makeText(OrderHeader.this, StrMsg, Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(OrderHeader.this,
							"Please check the network connection!!!",
							Toast.LENGTH_SHORT).show();
				}

			} catch (Exception ex) {

				ex.printStackTrace();

			}

		}

	}// Sync End

	private volatile boolean running = true;
	// The listener for all printer events
	private final ProtocolAdapter.ChannelListener mChannelListener = new ProtocolAdapter.ChannelListener() {
		@Override
		public void onReadEncryptedCard() {
			toast(getString(R.string.msg_read_encrypted_card));
		}

		@Override
		public void onReadCard() {
			// readMagstripe();
		}

		@Override
		public void onReadBarcode() {
			// readBarcode(0);
		}

		@Override
		public void onPaperReady(boolean state) {
			if (state) {
				toast(getString(R.string.msg_paper_ready));
			} else {
				toast(getString(R.string.msg_no_paper));
			}
		}

		@Override
		public void onOverHeated(boolean state) {
			if (state) {
				toast(getString(R.string.msg_overheated));
			}
		}

		@Override
		public void onLowBattery(boolean state) {
			if (state) {
				toast(getString(R.string.msg_low_battery));
			}
		}
	};

	private void SetPrinterConnection() {
		printerfound = false;
		String deviceAddress = "";
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
				.getBondedDevices();
		if (mPairedDevices.size() > 0) {
			for (BluetoothDevice mDevice : mPairedDevices) {
				if (mDevice.getName().equals(setting.PrinterName)) {
					deviceAddress = mDevice.getAddress();
					printerfound = true;
					break;
				}
			}
		}
		if (!printerfound) {
			return;
		}
		if (BluetoothAdapter.checkBluetoothAddress(deviceAddress)) {
			establishBluetoothConnection(deviceAddress);
		}
	}

	private void establishBluetoothConnection(final String address) {

		doJob(new Runnable() {
			@Override
			public void run() {
				BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
				BluetoothDevice device = adapter.getRemoteDevice(address);
				UUID uuid = UUID
						.fromString("00001101-0000-1000-8000-00805F9B34FB");
				InputStream in = null;
				OutputStream out = null; 
				adapter.cancelDiscovery(); 
				try {
					mBluetoothSocket = device
							.createRfcommSocketToServiceRecord(uuid);
					mBluetoothSocket.connect();
					in = mBluetoothSocket.getInputStream();
					out = mBluetoothSocket.getOutputStream();
				} catch (IOException e) {
					e.printStackTrace();
					error(getString(R.string.msg_failed_to_connect) + ". "
							+ e.getMessage(), mRestart);
					running = false;
					return;
				}

				try {
					initPrinter(in, out);
				} catch (IOException e) {
					e.printStackTrace();
					error(getString(R.string.msg_failed_to_init) + ". "
							+ e.getMessage(), mRestart);
					running = false;
					return;
				}

			}
		}, R.string.msg_connecting);
	}

	protected void initPrinter(InputStream inputStream,
			OutputStream outputStream) throws IOException {
		mProtocolAdapter = new ProtocolAdapter(inputStream, outputStream);

		if (mProtocolAdapter.isProtocolEnabled()) {
			final ProtocolAdapter.Channel channel = mProtocolAdapter
					.getChannel(ProtocolAdapter.CHANNEL_PRINTER);
			channel.setListener(mChannelListener);
			// Create new event pulling thread
			new Thread(new Runnable() {
				@Override
				public void run() {
					while (true) {
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

						try {
							channel.pullEvent();
						} catch (IOException e) {
							e.printStackTrace();
							error(e.getMessage(), mRestart);
							break;
						}
					}
				}
			}).start();
			mPrinter = new Printer(channel.getInputStream(),
					channel.getOutputStream());
		} else {
			mPrinter = new Printer(mProtocolAdapter.getRawInputStream(),
					mProtocolAdapter.getRawOutputStream());
		}

		mPrinterInfo = mPrinter.getInformation();

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				/*
				 * ((ImageView) findViewById(R.id.icon))
				 * .setImageResource(R.drawable.icon); ((TextView)
				 * findViewById(R.id.name)).setText(mPrinterInfo .getName());
				 */
			}
		});
	}

	private void error(final String text, boolean resetConnection) {
		if (resetConnection) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), text,
							Toast.LENGTH_SHORT).show();
				}
			});
			waitForConnection();
		}
	}

	private void toast(final String text) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (!isFinishing()) {
					Toast.makeText(getApplicationContext(), text,
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	} 
 
	private void dialog(final int iconResId, final String title,
			final String msg) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						OrderHeader.this);
				builder.setIcon(iconResId);
				builder.setTitle(title);
				builder.setMessage(msg);

				AlertDialog dlg = builder.create();
				dlg.show();
			}
		});
	}

	public synchronized void waitForConnection() {
		closeActiveConnection();
		SetPrinterConnection();
	}

	private synchronized void closeActiveConnection() {
		closePrinterConnection();
		closeBlutoothConnection();
	}

	private synchronized void closeBlutoothConnection() {
		BluetoothSocket s = mBluetoothSocket;
		mBluetoothSocket = null;
		if (s != null) {
			try {
				s.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private synchronized void closePrinterConnection() {
		if (mPrinter != null) {
			mPrinter.release();
		}

		if (mProtocolAdapter != null) {
			mProtocolAdapter.release();
		}
	}

	private void doJob(final Runnable job, final int resId) {
		// Start the job from main thread
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// Progress dialog available due job execution
				try {
					final ProgressDialog dialog = new ProgressDialog(
							OrderHeader.this);
					dialog.setTitle(getString(R.string.title_please_wait));
					dialog.setMessage(getString(resId));
					dialog.setCancelable(false);
					dialog.setCanceledOnTouchOutside(false);
					dialog.show();
					Thread t = new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								job.run(); 
							}catch (Exception e) {
								e.printStackTrace();
							}finally {
								dialog.dismiss();
							}
						}
					});
					if (running) { 
						t.start(); 
					} else {
						dialog.dismiss();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void onBackPressed() { 
		GoBack(); 
	}
	
	private void GoBack(){  
		OrderTab parent = (OrderTab) getParent();
		Intent _intent = new Intent();
		Bundle b = new Bundle();
		if (parent.Screen.equals("")) {
			b.putString("Code", CustCode);
			b.putString("CName", CName);
			b.putString("TrnType", TrnType);
		} else {
			b.putString("TrnType", "");
		}
		_intent.putExtras(b);
		_intent.setClass(OrderHeader.this, OrderSummary.class);
		startActivity(_intent); 
		this.finish();
	}

	
	private ArrayList<TrnDetail> getListCart() {
		objDBHelper = new DatabaseHelper(this);
		return objDBHelper.GetOrderDetailByHeaderId(CurrentTableDetail,String.valueOf(Header.Id));
	}

	

	private void printOrder(final boolean IsDO) {
		doJob(new Runnable() {
			@Override
			public void run() {  
				for( int i=0; i<NoOfReceipt;i++){  
				StringBuffer sb = new StringBuffer();
				PrintLayout ObjLayout=new PrintLayout(); 
				if(setting.PrintLayout.equals("Layout1"))
				{ 
					sb=ObjLayout.Layout1(OrderHeader.this,TrnType, CName, GSTInc, GST, IsDO, setting, Header, getListCart());
				}else if(setting.PrintLayout.equals("Layout2"))
				{ 
					sb=ObjLayout.Layout2(OrderHeader.this,TrnType, CName, GSTInc, GST, IsDO, setting, Header, getListCart());
				}
				try {
					mPrinter.reset();
					if (logoHeader != null) {
						final int width = logoHeader.getWidth();
						final int height = logoHeader.getHeight();
						final int[] argb = new int[width * height];
						logoHeader.getPixels(argb, 0, width, 0, 0, width, height);
						// logo.recycle();
						mPrinter.printImage(argb, width, height,
								Printer.ALIGN_CENTER, true);
					}
					 
					
					String strSB=sb.toString();
					String pt=new String(strSB.getBytes(Charset.forName("UTF-8")), Charset.forName("GB2312")); 
					mPrinter.printTaggedText(pt); 
					//mPrinter.printTaggedText(sb.toString()); 
					if(setting.PrintLayout.equals("Layout2"))
					{ 
						mPrinter.feedPaper(30);
						mPrinter.setBarcode(Printer.ALIGN_CENTER, true, 2, Printer.HRI_BELOW, 75);
	        			mPrinter.printBarcode(Printer.BARCODE_CODE128AUTO, Header.DocNo); 
					} 
					
					if (logoFooter != null) {
						mPrinter.feedPaper(20);
						final int width = logoFooter.getWidth();
						final int height = logoFooter.getHeight();
						final int[] argb = new int[width * height];
						logoFooter.getPixels(argb, 0, width, 0, 0, width, height);
						// logo.recycle();
						mPrinter.printImage(argb, width, height,
								Printer.ALIGN_CENTER, true);
					}
					mPrinter.feedPaper(110);
					mPrinter.flush();
				} catch (IOException e) {
					e.printStackTrace();
					error(getString(R.string.msg_failed_to_print_text) + ". "
							+ e.getMessage(), mRestart);
				}
				}
			}
		}, R.string.msg_printing_text);
	}

}
